
package com.trydofor.id.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Statement;

import javax.sql.DataSource;

import org.h2.jdbcx.JdbcDataSource;

/**
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public final class H2DataSource {
    
    private static final String H2JDBC = "jdbc:h2:mem:";
    
    public static DataSource getMemDataSource(String name) {
        JdbcDataSource datasource = new JdbcDataSource();
        datasource.setURL(H2JDBC + name);
        return datasource;
    }
    
    public static void excuteSqlscript(DataSource ds, InputStream script) throws Exception {
        Statement sst = null;
        BufferedReader br = null;
        try {
            sst = ds.getConnection().createStatement();
            br = new BufferedReader(new InputStreamReader(script));
            StringBuilder sb = new StringBuilder();
            while (true) {
                String ln = br.readLine();
                if (ln == null) break;
                if (ln.equalsIgnoreCase("GO")) {
                    sst.execute(sb.toString());
                    sb.delete(0, sb.length());
                }
                else {
                    sb.append(ln).append('\n');
                }
            }
            
        }
        finally {
            try {
                if (sst != null) sst.close();
            }
            catch (Exception e) {}
            try {
                if (br != null) br.close();
            }
            catch (Exception e) {}
            
        }
    }
}
